<script setup>
import { ref, computed, onMounted } from 'vue'
import { Api } from '@/api'
import defaultImage from '@/assets/zhishi.png'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

const articles = ref([])
const loading = ref(true)
const error = ref(null)
const searchQuery = ref('')

// 获取用户信息
const userStore = useUserStore()
const canManage = computed(() => {
  const user = userStore.user
  return user?.is_counselor || user?.is_admin
})

// 搜索过滤文章
const filteredArticles = computed(() => {
  if (!searchQuery.value.trim()) {
    return articles.value
  }
  return articles.value.filter(
    (article) =>
      article.title.includes(searchQuery.value) || article.content.includes(searchQuery.value),
  )
})

const baseURL = 'http://localhost:4000'

// 从后端获取心理知识数据
const fetchArticles = async () => {
  try {
    loading.value = true
    const response = await Api.getPsychologyKnowledgeList()
    if (response.data && Array.isArray(response.data.data)) {
      articles.value = response.data.data.map((article) => {
        let imageUrl = defaultImage
        try {
          const pictures = JSON.parse(article.picture || '[]')
          if (pictures && pictures.length > 0) {
            // 检查是否是完整的URL
            imageUrl = pictures[0].startsWith('http') ? pictures[0] : `${baseURL}${pictures[0]}`
          }
        } catch (error) {
          console.error('解析图片字段失败:', error)
        }

        // 清理文章内容，移除HTML标签
        const cleanContent = article.content ? article.content.replace(/<\/?[^>]+(>|$)/g, '').trim() : ''
        const cleanTitle = article.title ? article.title.replace(/<\/?[^>]+(>|$)/g, '').trim() : ''

        return {
          ...article,
          image: imageUrl,
          content: cleanContent,
          title: cleanTitle
        }
      })
    } else {
      console.error('后端返回的数据格式不正确:', response.data)
      throw new Error('数据格式错误')
    }
  } catch (err) {
    error.value = '加载心理知识失败，请稍后再试'
    console.error('获取心理知识数据失败:', err)
  } finally {
    loading.value = false
  }
}

const router = useRouter()

// 跳转到管理页面
const goToManage = () => {
  router.push('/articles/manage')
}

const goToArticleDetail = (articleId) => {
  if (!articleId) {
    console.error('文章 ID 无效')
    return
  }
  router.push(`/articles/${articleId}`)
}

onMounted(() => {
  fetchArticles()
})
</script>

<template>
  <div class="articles">
    <div class="banner">
      <h1>心理知识</h1>
      <p>专业的心理健康知识分享，助您更好地了解自己</p>
    </div>

    <div class="content">
      <!-- 搜索和管理工具栏 -->
      <div class="toolbar">
        <div class="search-container">
          <input
            type="text"
            v-model="searchQuery"
            placeholder="搜索文章标题或内容..."
            class="search-input"
          />
        </div>
        <div v-if="canManage" class="admin-tools">
          <el-button type="primary" @click="goToManage()">文章管理</el-button>
        </div>
      </div>

      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="error" class="error">{{ error }}</div>
      <div v-else class="article-grid">
        <div
          v-for="article in filteredArticles"
          :key="article.id"
          class="article-card"
          @click="goToArticleDetail(article.id)"
        >
          <img
            :src="article.image"
            :alt="article.title"
            @error="(e) => (e.target.src = defaultImage)"
          />
          <div class="article-content">
            <h2>{{ article.title }}</h2>
            <p v-html="article.content.replace(/<\/?[^>]+(>|$)/g, '')"></p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.articles {
  padding-top: 60px;
}

.banner {
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('/articles-banner.jpg');
  background-size: cover;
  background-position: center;
  color: white;
  text-align: center;
  padding: 4rem 1rem;
  margin-bottom: 2rem;
}

.banner h1 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
}

.content {
  max-width: 1200px;
  margin: 2rem auto;
  padding: 0 1rem;
}

.toolbar {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.search-container {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.search-input {
  width: 100%;
  max-width: 400px;
  padding: 0.5rem 1rem;
  border: 1px solid #ccc;
  border-radius: 20px;
  font-size: 1rem;
}

.admin-tools {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding: 0 1rem;
}

.article-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 2rem;
}

.article-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
  cursor: pointer;
}

.article-card:hover {
  transform: translateY(-5px);
}

.article-card img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.article-content {
  padding: 1.5rem;
}

.article-content h2 {
  margin: 1rem 0;
  font-size: 1.2rem;
  line-height: 1.4;
}

.article-content p {
  color: #666;
  line-height: 1.6;
  font-size: 0.9rem;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.loading,
.error {
  text-align: center;
  font-size: 1.2rem;
  margin: 20px 0;
}

.error {
  color: #ff4444;
}

@media (max-width: 768px) {
  .article-grid {
    grid-template-columns: 1fr;
  }
}
</style>
